package at.fhv.androideightpuzzle.network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import at.fhv.androideightpuzzle.network.message.IMessage;

public abstract class NetworkServerSocket extends Observable implements Observer{
	
	protected ConnectionType m_connType;
	protected List<NetworkSocket> m_clients;
	//protected List<String> m_clientNames;
	
	public NetworkServerSocket(ConnectionType connectionType){
		m_connType=connectionType;
		m_clients=new ArrayList<NetworkSocket>();
		//m_clientNames=new ArrayList<String>();
	}
	
	public abstract void startAccepting() throws IOException;
	
	public abstract void stopAccepting() throws IOException;
	
	public void closeSockets(){
		for(NetworkSocket socket:m_clients){
			try{
				socket.close();
			}catch(IOException exc){
				android.util.Log.e("NetworkServerSocket",exc.getMessage(),exc);
			}
		}
	}
	
	/*public void addClientName(String name){
		if((name!=null) && (name.equals("")==false)){
			m_clientNames.add(name);
		}
	}
	
	public String[] getClientNames(){
		String[] clientNames=null;
		
		synchronized(m_clients){
			clientNames=new String[m_clients.size()];
			
			for(int i=0; i<clientNames.length; i++){
				clientNames[i]=m_clients.get(i).toString();
			}
		}
		
		return clientNames;
		//return m_clientNames.toArray(new String[0]);
	}*/
	
	public List<NetworkSocket> getClients(){
		return m_clients;
	}
	
	public ConnectionType getConnectionType(){
		return m_connType;
	}
	
	public void update(Observable observable,Object argument){
		if(observable instanceof NetworkSocket){
			if(argument instanceof IMessage){
				setChanged();
				notifyObservers(argument);
			}
		}
	}
}
